
const app =  getApp();

Page({
  data: {
    result:"",
    lists:"",
    keyword:"",
    res:"",
    visitedCities:[],
    location:""
  },
  onLoad: function (options) {
    /* 根据缓存设置当前定位的城市 */
    var location = wx.getStorageSync('locationCity')
    this.setData({
      location
    })

    /* 从缓存中获取最近访问的城市 */
    var cities = wx.getStorageSync('cities')
    if(cities){
      this.setData({
        visitedCities:cities
      })
    }else{
      wx.setStorageSync('cities', [])
    }
    wx.request({
      url: 'http://192.168.4.18:8000/city',
      header: {'content-type':'application/json'},
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: (res)=>{
        var result = res.data.data
        var lists = Object.keys(result.cities)
        this.setData({
          result,
          lists
        })
      }
    });
  },
  /* 点击城市切换并且将点击过的添加到缓存中 */
  handleClick(event){
    var cities = wx.getStorageSync('cities')
    var name = event.currentTarget.dataset.name
    if(!cities.includes(name)){
      cities.unshift(name)
    }
    wx.setStorageSync('cities', cities.slice(0,3))
    app.globalData.currentCity = name
    wx.navigateBack();
  },
  /* 在搜索框中输入要查找的城市 */
  onChange(event){
    var keyword = event.detail.trim()
    var res = this.filterCity(keyword)
    this.setData({
      keyword,
      res
    })
  },
  /* 根据关键字查找符合条件的城市 */
  filterCity(keyword){
    var cities = this.data.result.cities
    var arr = []
    for(var key in cities){
      cities[key].forEach(item=>{
        if(item.name.includes(keyword)||item.spell.includes(keyword)){
          arr.push(item)
        }
      })
    }
    return arr
  }
})